#include "Arduino.h"
#include "esp_adc_cal.h"
#include "driver/adc.h"

#ifndef GET_PWR_VAL_H
#define GET_PWR_VAL_H

#define R4 4700 // 4.7k
#define R2 1000 // 1k

#define bat_switch_pin  2          // 电池电压读取开关
#define bat_vcc_pin     1          // 读取电池电压引脚，不能超过3.3V(0~3.3 <=> 0~4095)
#define READ_COUNT      30

void pwr_adc_init() {
  analogReadResolution(12); // 0~4095
  // analogSetPinAttenuation(ADC_ATTEN_DB_11, ); // 默认是11, 150mV~2450mV
}

// 一次adc检测
void once_adc_test() {
  pinMode(bat_switch_pin, OUTPUT);
  digitalWrite(bat_switch_pin, 1);
  float adc_reading = 0; // 用于存储ADC volt读数的累加和

  for (int i = 0; i < READ_COUNT; i++) {
      adc_reading += analogReadMilliVolts(bat_vcc_pin) / 1000.0;
      delay(1); // 采集每个样本之间加入1ms的延迟
  }

  // 计算ADC读数的平均值
  adc_reading /= READ_COUNT;
  
  Serial.print("Voltage R2: ");
  Serial.println(adc_reading);//打印R2的电压值
  adc_reading = (adc_reading * (R4 + R2)) / R2;
  Serial.print("Voltage with resistors: ");
  Serial.println(adc_reading);//打印总电压值

  digitalWrite(bat_switch_pin, 0); //关闭电池测量
  pinMode(bat_switch_pin, INPUT);  //改为输入状态避免漏电

  // 每秒打印一次读数
  delay(1000);
}

float get_pwr_vol() {
  pinMode(bat_switch_pin, OUTPUT);
  digitalWrite(bat_switch_pin, 1);
  float adc_reading = 0.0; // 用于存储ADC volt读数的累加和

  for (int i = 0; i < READ_COUNT; i++) {
      adc_reading += analogReadMilliVolts(bat_vcc_pin) / 1000.0;
      delay(1); // 采集每个样本之间加入1ms的延迟
  }
  digitalWrite(bat_switch_pin, 0); //关闭电池测量
  pinMode(bat_switch_pin, INPUT);  //改为输入状态避免漏电
  // 计算ADC读数的平均值
  adc_reading /= READ_COUNT;
  adc_reading = (adc_reading * (R4 + R2)) / R2;
  return adc_reading;
}

float get_pwr_val_log() {
    pinMode(bat_switch_pin, OUTPUT);
    digitalWrite(bat_switch_pin, 1);
    delay(1);
    float vcc_cache = 0.0;
    for (uint8_t i = 0; i < 30; i++)
    {
      delay(1);
      vcc_cache += analogRead(bat_vcc_pin); // analog[0~4095] * 1 / 4096
    }
    digitalWrite(bat_switch_pin, 0); //关闭电池测量
    pinMode(bat_switch_pin, INPUT);  //改为输入状态避免漏电
    return (vcc_cache / 30);
}

#endif